import 'package:flutter/material.dart';
import 'package:sjx/repository/sjx_api.dart';

import '../../../repository/model/sale_coin_model.dart';
import '../../../utils/sp_utils.dart';

class SaleCoinViewModel extends ChangeNotifier {
  // 状态变量
  SaleCoinModel? _saleCoinInfo;
  int _coinAmount = 0;
  double _rate = 0.0;
  bool _isLoading = false;
  bool _hasError = false;
  String _errorMessage = '';

  // 添加回调函数用于更新文本控制器
  VoidCallback? _onCoinAmountChanged;

  // Getter 方法
  SaleCoinModel? get saleCoinInfo => _saleCoinInfo;
  int get coinAmount => _coinAmount;
  double get rate => _rate;
  bool get isLoading => _isLoading;
  bool get hasError => _hasError;
  String get errorMessage => _errorMessage;

  // 计算属性
  int get availableCoins => _saleCoinInfo?.balanceCoinAmount ?? 0;
  double get expectedAmount => _coinAmount == 0
      ? 0.0
      : (_coinAmount * _rate);
  bool get canSubmit => _coinAmount > 0;

  void setOnCoinAmountChanged(VoidCallback callback) {
    _onCoinAmountChanged = callback;
  }

  // 加载金币信息
  Future<void> loadCoinInfo() async {
    _setLoading(true);

    try {
      _saleCoinInfo = await SJXApi.instance().userCoinAmount();
      _rate = _saleCoinInfo!.coinConvertRatio ?? 0.0;
      _hasError = false;
      _errorMessage = '';
    } catch (e) {
      _hasError = true;
      _errorMessage = e.toString();
    } finally {
      _setLoading(false);
    }
  }

  // 设置金币数量
  void setCoinAmount(int amount) {
    _coinAmount = amount;
    _onCoinAmountChanged?.call();
    notifyListeners();
  }

  // 全部出售
  void sellAll() {
    _coinAmount = availableCoins;
    _onCoinAmountChanged?.call();
    notifyListeners();
  }

  // 提交出售
  Future<bool> submitSale() async {
    if (!canSubmit) return false;

    _setLoading(true);

    try {
      final user = await SpUtils.getUserData();
      final params = {
        'coinAmount': _coinAmount,
        'moneyAmount': expectedAmount,
        'platformId': user!.platformId,
      };
      await SJXApi.instance().userSaleCoin(params);
      return true;
    } catch (e) {
      _hasError = true;
      _errorMessage = e.toString();
      return false;
    } finally {
      _setLoading(false);
    }
  }

  // 验证输入
  String? validateInput(String value) {
    if (value.isEmpty) return null;

    // 检查是否为数字
    if (double.tryParse(value) == null) {
      return '您输入的格式不正确';
    }

    // 检查是否包含小数点
    if (value.contains('.')) {
      return '不能输入小数点';
    }

    // 检查首位是否为0
    if (value.startsWith('0') && value.length > 1) {
      return '第一个数字不能为0';
    }

    // 检查是否超出可售金币数
    final inputValue = double.parse(value);
    final availableValue = availableCoins ?? 0;
    if (inputValue > availableValue) {
      return '超出可售金币数';
    }

    return null;
  }

  // 清除错误
  void clearError() {
    _hasError = false;
    _errorMessage = '';
    notifyListeners();
  }

  void _setLoading(bool loading) {
    _isLoading = loading;
    notifyListeners();
  }
}